const CryptoJS = require('crypto-js');
const request = require('request');


const AppId     = "xxxxxxxx";           //APPID
const AppSecret = "xxxxxxxx";           //密钥
const ApiUrl    = "https://iot-app-prod.fengdada.cn/mk/api";    //API地址
const PrinterId = "xxxxxxxx";                            //打印机ID

function encode(jsonData, nonce) {
  const jsonBytes = Buffer.from(jsonData, 'utf-8');
  const bizData = jsonBytes.toString('utf-8');
  const sign_ori = `${bizData}${nonce}${AppSecret}`;
  let hash = CryptoJS.MD5(sign_ori);
  let wordArray = hash.words;
  CryptoJS.lib.WordArray.create(wordArray).clamp();
  let sign = CryptoJS.enc.Base64.stringify(hash);
  return sign;
}

function generateVerificationCode() {
  let verificationCode = '';
  for (let i = 0; i < 6; i++) {
    verificationCode += Math.floor(Math.random() * 10);
  }
  return verificationCode;
}

function DoMyPost(URL, json_BizData) {
  const ts = Date.now();
  const nonce = generateVerificationCode();
  const sign = encode(json_BizData, nonce);
  const data = {
    "bizData": json_BizData,
    "nonce": nonce,
    "appId": AppId,
    "timestamp": String(ts)
  };

  const headers = { "Content-Type": "application/json", "sign": sign };
  
  request({
    url: URL,
    method: 'POST',
    headers: headers,
    json: data
  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body);
    } else {
      console.log('request failed');
    }
  });
}
//1、获取验证码
function PrintCaptcha() {
    const URL = ApiUrl+"/print/captcha";
    let BizData = {'printerId': PrinterId};
    let json_BizData = JSON.stringify(BizData);
    DoMyPost(URL, json_BizData);
}

//2、绑定打印机
function PrintBind(VerificationCode){
    const URL = ApiUrl+"/printer/bind"
    let BizData = {'printerId': PrinterId,'captcha':VerificationCode}
    let json_BizData = JSON.stringify(BizData);
    DoMyPost(URL, json_BizData)
}
//3、云打印
function Print(ShareCode,TemplateId){
    const URL = ApiUrl+"/print"
    const waybillPrinterData = {
        "receiveManAddress":"塘苗路18号",
        "orderId":"10256485649",
        "needFetch":"true",
        "packageWeight":"",
        "companyName":"",
        "sendProvince":"浙江省",
        "errorCode":"",
        "receiverProvince":"浙江省",
        "receiverCity":"杭州市",
        "senderMan":"张三",
        "senderArea":"西湖区",
        "receiveMan":"李四",
        "postStationId":"",
        "itemName":"",
        "specialType":"代收货款",
        "senderPostcode":"",
        "payMethod":"0",
        "id":"1933",
        "logisticCode":"BestSmart10256485649",
        "machineCode":"1843923524226238",
        "errorDesc":"",
        "balanceStatus":"",
        "specialMoney":" 39 元",
        "expressType":"0",
        "sendCounty":"西湖区",
        "weight":"",
        "receiverPostcode":"",
        "version":"1",
        "senderCity":"杭州市",
        "receiveProvince":"浙江省",
        "printResult":"NONE",
        "sendMan":"张三",
        "companyId":"",
        "expressCost":"",
        "receiverManPhone":"18598765432",
        "mainId":"",
        "senderManPhone":"15012345678",
        "remark1":"",
        "remark3":"",
        "receiveCounty":"西湖区",
        "remark2":"",
        "lastUpdateTime":"Wed Jul 29 13:53:06 CST 2015",
        "markDestination":"测-测试单(2)(浙-2)",
        "sendCity":"杭州市",
        "pkgCode":"测试测试包",
        "receiverMan":"李四",
        "errorInfo":"null",
        "remark":"【批次1/1】备注",
        "sendManPhone":"15012345678",
        "batchId":"1/1",
        "pickBy":"",
        "result":"SUCCESS",
        "mailNo":"12345678901234",
        "shippingStatus":"NOMESSAGE",
        "serialVersionUID":"-1229572053273904313",
        "richItemInformation":"",
        "receiveManPhone":"18598765432",
        "udf7":"",
        "billProvideSiteCode":"200000",
        "logisticsProviderCode":"HTKY",
        "udf8":"",
        "printCount":"1",
        "senderManAddress":"教工路1号",
        "custId":"null",
        "itemWeight":"",
        "receiverManAddress":"塘苗路18号",
        "isReprint":"false",
        "orderSource":"BestSmart",
        "udf5":"测试",
        "udf6":"",
        "senderProvince":"浙江省",
        "receiverArea":"西湖区",
        "udf3":"",
        "udf4":"",
        "udf1":"",
        "userId":"",
        "udf2":"",
        "postStationName":"",
        "itemCount":"0",
        "logisticProviderID":"HTKY",
        "billProvideSiteName":"上海分拨中心",
        "createTime":"Wed Jul 29 13:37:40 CST 2015",
        "receiveCity":"杭州市",
        "sendManAddress":"教工路1号",
        "printTime":"",
        "username":""
        };
    const printDataList = [{"waybillPrinterData": waybillPrinterData, "templateId": TemplateId}];
    let BizData = {'printerId': PrinterId,'shareCode':ShareCode,'printData':printDataList}
    let json_BizData = JSON.stringify(BizData);
    DoMyPost(URL, json_BizData)
}
//4、云打印机状态查询
function QueryPrintStatus(ShareCode){
    const URL = ApiUrl+"/printer/status/query"
    let BizData = {'printerId': PrinterId,'shareCode':ShareCode}
    let json_BizData = JSON.stringify(BizData);

    console.log("shareCode=",ShareCode);

    DoMyPost(URL, json_BizData)
  }

//入口
//1、获取验证码
//PrintCaptcha();  
//2、绑定打印机
//const VerificationCode="xxxxxx";
//PrintBind(VerificationCode);
//3、云打印
//const ShareCode="xxxxxx";
//const TemplateId="xxx"
//Print(ShareCode,TemplateId);

//4、云打印机状态查询
//QueryPrintStatus(ShareCode);